package agents.election;

import java.util.Comparator;

import agents.TrafficLightAgent;

public class GroupElectionJudge implements Comparator<GroupBallot> {
	
	private static GroupElectionJudge instance = null;

	public static GroupElectionJudge getInstance() {
		if(instance == null)
			instance = new GroupElectionJudge();
		
		return instance;
	}

	@Override
	public int compare(GroupBallot g1, GroupBallot g2) {
		if(g1 == null)
			return -1;
		else if(g2 == null)
			return 1;
		
		TrafficLightAgent ag1 = g1.getAgent();
		TrafficLightAgent ag2 = g2.getAgent();
		int acount1 = ag1.getSuccessors().size();
		int acount2 = ag2.getSuccessors().size();
		
		if(acount1 > acount2)
			return 1;
		else if(acount1 < acount2)
			return -1;
		else { // DESEMPATE
			double succsize1 = 0;
			double succsize2 = 0;
			
			for(TrafficLightAgent agent : ag1.getSuccessors())
				succsize1 += agent.getEdge().getWeight();
			for(TrafficLightAgent agent : ag2.getSuccessors())
				succsize2 += agent.getEdge().getWeight();
			
			if(succsize1 > succsize2)
				return 1;
			else if(succsize1 < succsize2)
				return -1;
			else { // DESEMPATE
				double asize1 = ag1.getEdge().getWeight();
				double asize2 = ag1.getEdge().getWeight();
				
				if(asize1 > asize2)
					return 1;
				else if(asize1 < asize2)
					return -1;
				else { // DESEMPATE
					if(g1.getRand() > g2.getRand())
						return 1;
					else if(g1.getRand() < g2.getRand())
						return -1;
					else { // DESEMPATE
						if(ag1.hashCode() > ag2.hashCode())
							return 1;
						else if(ag1.hashCode() < ag2.hashCode())
							return -1;
						else { // DESEMPATE - PUTZ!!!
							if(g1.hashCode() < g2.hashCode())
								return 1;
							else if(g1.hashCode() > g2.hashCode())
								return -1;
							// ELSE => São iguais!!!
						}
					}
				}
			}
		}
		
		return 0;
	}

}
